package com.business.dashboard.controller;

import com.business.dashboard.entity.NewsArticle;
import com.business.dashboard.service.NewsArticleService;
import com.business.dashboard.utils.ResultUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotNull;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户端新闻控制器
 * 
 * @author Claude
 * @since 2025-07-08
 */
@Slf4j
@RestController
@RequestMapping("/api/news")
@Validated
public class NewsController {

    @Autowired
    private NewsArticleService newsArticleService;

    /**
     * 获取已发布的新闻文章列表（公开接口）
     */
    @GetMapping("")
    public ResultUtil<Map<String, Object>> getPublishedNews(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "20") Integer limit,
            @RequestParam(required = false) String category,
            @RequestParam(defaultValue = "published") String status) {
        try {
            // 只返回已发布的新闻
            List<NewsArticle> newsList = newsArticleService.getPublishedNews(page, limit, category);
            Long total = newsArticleService.getPublishedNewsCount(category);
            
            Map<String, Object> result = new HashMap<>();
            result.put("data", newsList);
            result.put("total", total);
            result.put("page", page);
            result.put("limit", limit);
            
            return ResultUtil.success("获取新闻列表成功", result);
        } catch (Exception e) {
            log.error("获取新闻列表失败", e);
            return ResultUtil.error("获取新闻列表失败：" + e.getMessage());
        }
    }

    /**
     * 根据ID获取新闻文章详情（公开接口）
     */
    @GetMapping("/{id}")
    public ResultUtil<NewsArticle> getNewsById(@PathVariable @NotNull Long id) {
        try {
            NewsArticle news = newsArticleService.getNewsById(id);
            if (news == null) {
                return ResultUtil.error(404, "新闻不存在");
            }
            
            // 只返回已发布的新闻
            if (!"published".equals(news.getStatus())) {
                return ResultUtil.error(404, "新闻不存在");
            }
            
            // 增加浏览量
            newsArticleService.incrementViewCount(id);
            
            return ResultUtil.success("获取新闻详情成功", news);
        } catch (Exception e) {
            log.error("获取新闻详情失败，ID: {}", id, e);
            return ResultUtil.error("获取新闻详情失败：" + e.getMessage());
        }
    }

    /**
     * 获取热门新闻（公开接口）
     */
    @GetMapping("/hot")
    public ResultUtil<List<NewsArticle>> getHotNews(
            @RequestParam(defaultValue = "5") Integer limit) {
        try {
            List<NewsArticle> hotNews = newsArticleService.getHotNews(limit);
            return ResultUtil.success("获取热门新闻成功", hotNews);
        } catch (Exception e) {
            log.error("获取热门新闻失败", e);
            return ResultUtil.error("获取热门新闻失败：" + e.getMessage());
        }
    }

    /**
     * 获取最新新闻（公开接口）
     */
    @GetMapping("/latest")
    public ResultUtil<List<NewsArticle>> getLatestNews(
            @RequestParam(defaultValue = "10") Integer limit) {
        try {
            List<NewsArticle> latestNews = newsArticleService.getLatestNews(limit);
            return ResultUtil.success("获取最新新闻成功", latestNews);
        } catch (Exception e) {
            log.error("获取最新新闻失败", e);
            return ResultUtil.error("获取最新新闻失败：" + e.getMessage());
        }
    }

    /**
     * 搜索新闻（公开接口）
     */
    @GetMapping("/search")
    public ResultUtil<List<NewsArticle>> searchNews(
            @RequestParam String keyword,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "20") Integer limit) {
        try {
            List<NewsArticle> searchResults = newsArticleService.searchNews(keyword, page, limit);
            return ResultUtil.success("搜索新闻成功", searchResults);
        } catch (Exception e) {
            log.error("搜索新闻失败，关键词: {}", keyword, e);
            return ResultUtil.error("搜索新闻失败：" + e.getMessage());
        }
    }
}